<template>
  <div class="">
    <div style="display: flex">
      <h1>上传图片为网络图片</h1>
      <div class="submit-btn" @click="submit">确定上传</div>
    </div>
    <!-- <p>选择文件：</p> -->
    <div class="imgDiv" @click="clickBtn" ref="dropDiv">
      <div class="centerContent">
        <img src="./upload.png" alt="" class="centerContent-img">
        <div>将文件拖到此处,或点击上传</div>
      </div>
    </div>
    <input multiple type="file" accept="image/*" @change="upload" ref="upload" style="display: none" />
    <div class="imgs-title">
      {{httpUrls.length !== 0 ? '图片的网路资源地址' : '选择的图片列表'}}
    </div>
    <div class="imgs">
      <div v-for="(item, index) in imgUrls" :key="index" class="one-img">
        <img :src="item" alt="" />
        <div class="mask">
          <img class="mask-img" src="./del.png" alt="" @click="delImg(index)">
        </div>
      </div>
      <div v-for="(item, index) in httpUrls" :key="index" class="urls-div">
        {{item}}
        <span class="iconfont reco-document icon-copy" @click="copyUrl(item)"></span>
      </div>
    </div>
    <!-- 提示 -->
    <div class="show-title" v-show="showTitle">
      复制成功！
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      cos: null,
      reader: null,
      imgUrls: [],
      uploadDom: null,
      httpUrls: [],
      showTitle: false,
    }
  },
  created () {
    var COS = require('cos-js-sdk-v5');

    // SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
    this.cos = new COS({
        SecretId: 'AKIDgCTTCfHcgV4NQGsDH4brqX1FDuJSKvGL',
        SecretKey: 'pOhkW0D9pFOGrBE0XnmUv5yaw2B3e04r',
    })
    // this.reader = new FileReader();
    // console.log(this.cos)
    console.log(this)
  },
  mounted () {
    this.uploadDom = this.$refs.upload
    let dropBox = this.$refs.dropDiv
    dropBox.ondragenter = this.ignoreDrag;
    dropBox.ondragover = this.ignoreDrag;
    dropBox.ondrop = this.drop;
  },
  methods: {
    copyUrl (text) {
      this.showTitle = true
      let timer = setTimeout(() => {
        this.showTitle = false
        clearTimeout(timer)
      }, 1500)
      // navigator clipboard 需要https等安全上下文
      if (navigator.clipboard && !window.isSecureContext) {
          // navigator clipboard 向剪贴板写文本
          return navigator.clipboard.writeText(text);
      } else {
          // 创建text area
          let textArea = document.createElement("textarea");
          textArea.value = text;
          // 使text area不在viewport，同时设置不可见
          textArea.style.position = "absolute";
          textArea.style.opacity = 0;
          textArea.style.left = "-999999px";
          textArea.style.top = "-999999px";
          document.body.appendChild(textArea);
          textArea.focus();
          textArea.select();
          return new Promise((res, rej) => {
              // 执行复制命令并移除文本框
              document.execCommand('copy') ? res() : rej();
              textArea.remove();
          });
      }
    },
    clickBtn () {
      this.uploadDom.click()
    },
    upload (e, type) {
      let imgs
      if (type) {
        imgs = e
      } else {
        imgs = this.$refs.upload.files
      }
      for (let key in imgs) {
        if (typeof imgs[key] === 'object') {
          // 每个reader监听一个
          let reader = new FileReader()
          reader.onload = (e) => {
            console.log(e)
            this.imgUrls.push(e.currentTarget.result)
          }
          reader.readAsDataURL(imgs[key])
        }
      }
      this.httpUrls = []
    },
    ignoreDrag(e) {
      //因为我们在处理拖放，所以应该确保没有其他元素会取得这个事件
      e.stopPropagation();
      e.preventDefault();
    },
    drop(e) {
      //取消事件传播及默认行为
      e.stopPropagation();
      e.preventDefault();
      
      //取得拖进来的文件
      var data = e.dataTransfer;
      var files = data.files;
      //将其传给真正的处理文件的函数
      this.upload(files, 'drop');
      // console.log(files)
    },
    delImg (index) {
      this.imgUrls.splice(index, 1)
    },
    submit () {
      if (this.imgUrls.length === 0) return
      let keys = []
      let files = []
      this.imgUrls.map((item, index) => {
        let body = this.dataURLtoBlob(item)
        let Key = this.getDateKey() + index
        keys.push(Key)
        files.push({
          Bucket: 'zelma-img-1304519255', /* 填入您自己的存储桶，必须字段 */
          Region: 'ap-chengdu',  /* 存储桶所在地域，例如ap-beijing，必须字段 */
          Key,  /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
          Body: body
        })
        // this.cos.putObject({
        //     Bucket: 'zelma-img-1304519255', /* 填入您自己的存储桶，必须字段 */
        //     Region: 'ap-chengdu',  /* 存储桶所在地域，例如ap-beijing，必须字段 */
        //     Key,  /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        //     Body: body,
        // }, function(err, data) {
        //     console.log(err || data);
        // });
      })
      let _this = this
      this.cos.uploadFiles({
          files,
          SliceSize: 1024 * 1024 * 10,    /* 设置大于10MB采用分块上传 */
          onProgress: function (info) {
              var percent = parseInt(info.percent * 10000) / 100;
              var speed = parseInt(info.speed / 1024 / 1024 * 100) / 100;
              console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
          },
          onFileFinish: function (err, data, options) {
              console.log(options.Key + '上传' + (err ? '失败' : '完成'));
          },
      }, function (err, data) {
          console.log(err || data);
          if (data.files) {
            data.files.map(item => {
              _this.httpUrls.push('https://' + item.data.Location)
              _this.imgUrls = []
              // console.log(_this.httpUrls)
            })
          }
      })
    },
    dataURLtoBlob (dataurl) {
      var arr = dataurl.split(',');
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    getDateKey () {
      // 比如需要这样的格式 yyyy-MM-dd hh:mm:ss
      var date = new Date(Date.now());
      let Y = date.getFullYear() + '-';
      let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
      let D = date.getDate() + ' ';
      let h = date.getHours() + ':';
      let m = date.getMinutes() + ':';
      let s = date.getSeconds(); 
      return Y+M+D+h+m+s;
      // 输出结果：2014-04-23 18:55:49
    }
  }
}
</script>
<style>
.imgs-title {
  margin-top: 10px;
  margin-bottom: 15px;
}
.submit-btn {
  background: #3eaf7c;
  width: 90px;
  height: 35px;
  text-align: center;
  line-height: 35px;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  margin-left: 30px;
  transition: all .8s;
  opacity: .7;
}
.submit-btn:hover {
  opacity: 1;
}
.imgDiv {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  width: 360px;
  height: 180px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}
.imgDiv:hover {
  border-color: #409eff;
}
.centerContent {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 14px;
  color: #606266;
}
.centerContent-img {
  width: 50px;
  height: 50px;
  margin-bottom: 5px;
}
.imgs {
  display: flex;
  flex-wrap: wrap;
  /* flex-direction: column; */
  /* margin-top: 20px; */
}
.one-img {
  width: 360px;
  height: 180px;
  margin-right: 20px;
  border-radius: 4px;
  margin-bottom: 10px;
  position: relative;
  overflow: hidden;
}
.one-img>img {
  min-width: 100%;
  min-height: 100%;
}
.one-img:hover .mask {
  opacity: 1;
  z-index: 1;
}
.mask {
  position: absolute;
  width: 360px;
  height: 180px;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, .5);
  transition: all .5s;
  opacity: 0;
  z-index: -1;
  display: flex;
  align-items: center;
  justify-content: center;
}
.mask-img {
  width: 50px;
  height: 50px;
  cursor: pointer;
}
.copy-span {
  opacity: 1;
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
  right: -50px;
  width: 40px;
  height: 20px;
  background: #3eaf7c;
  line-height: 20px;
  text-align: center;
  color: white;
  font-size: 13px;
  cursor: pointer;
  border-radius: 2px;
  transition: all .5s;
  user-select: none;
}
.icon-copy {
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
  right: -30px;
  color: #3eaf7c !important;
  font-size: 20px !important;
  cursor: pointer;
}
.urls-div {
   /* width: 100%; */
   margin-bottom: 10px;
   position: relative;
}
.urls-div:hover .copy-span {
  /* display: block; */
  opacity: 1;
}
.show-title {
  position: fixed;
  left: 50%;
  transform: translate(-50%, 0);
  top: 10%;
  width: 120px;
  height: 40px;
  border-radius: 5px;
  text-align: center;
  line-height: 40px;
  color: white;
  background: #84dbb4;
  /* opacit; */
}
</style>
